<!DOCTYPE HTML>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0, minimum-scale=1.0, user-scalable=0, initial-scale=1.0, width=device-width" />
    <meta name="format-detection" content="telephone=no, email=no, date=no, address=no">
    <title>消息中心</title>
    <link rel="stylesheet" type="text/css" href="../css/api.css" />
    <link rel="stylesheet" type="text/css" href="../css/utilCss.css">
    <script type="text/javascript" src="../script/api.js"></script>
    <script type="text/javascript" src="../script/jquery.js"></script>

    <style>
        html,
        body {
            height: 100%;
            width: 100%;
            overflow: hidden;
            margin: 0;
            padding: 0;
        }

        .lxb_div_abroad {
            background-color: #f7f7f7;

        }

        .lxb_div_abroad ul {height: 100%;overflow: scroll;background-color: #f7f7f7}
        .lxb_div_abroad_context {
            margin: 0px 15px 0 15px;
            background-color: #fff
        }

        .lxb_div_abroad_context li {padding: 2px;}

        .lxb_div_abroan_item {
            height: 66px;
            overflow: hidden;
            display: -webkit-box;
            border-radius: 3px;
            box-shadow: 0 0 1px 1px rgba(190, 190, 195, 0.25);
            background-color: #fff
        }

        .lxb_div_abroan_item_left {
            width: 66px;
            height: 66px;
            display: inline-block;
        }
        .lxb_div_abroan_item_left1 {
                    width: 46px;
                    height: 46px;
                    display: inline-block;
                    background-size: 46px;
                    background-repeat: no-repeat;
                    margin-left: 10px;
                    margin-top: 10px;
        }
        .lxb_div_abroan_item_left2{
          width: 10px;
          height: 10px;
          background-color: #fb1a34;
          border-radius: 10px;
          position: relative;
          right:6px;
          float: right;
          margin-top: 6px;
        }
        .lxb_div_abroan_item_right {
            -webkit-box-flex: 1.0;
            padding-top: 10px;
            padding-right: 13px;
        }
        .abroan_item_right1_left {
            display: inline-block;
            font-size: 15px;
            color: #353535;
        }
        .abroan_item_right1_right {
            float: right;
        }
        .abroan_item_right2 {
            margin-top: 6px
        }

        .abroan_item_right3{
          display: none;
        }

    </style>
</head>

<body>

    <div id="lxb_div_abroad_itemConText" style="display:none">
        <div style="height:13px;background-color:#f7f7f7"></div>
        <div class="lxb_div_abroan_item">
            <div class="lxb_div_abroan_item_left">
              <div class="lxb_div_abroan_item_left1"></div>
              <div class="lxb_div_abroan_item_left2"></div>
            </div>
            <div class="lxb_div_abroan_item_right">
                <div class="abroan_item_right1">
                    <div class="abroan_item_right1_left">
                    </div>
                    <div class="abroan_item_right1_right newslist_fram_abtoan_item_style1">
                    </div>
                </div>
                <div class="abroan_item_right2 newslist_fram_abtoan_item_style1">
                </div>
                <div class="abroan_item_right3"></div>
            </div>
        </div>
    </div>

    <div class="lxb_div_abroad">
        <ul class="lxb_div_abroad_context">
        </ul>
    </div>

</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript">
    var appJson;          //获取从app拿来的数据
    var dbData  = new Array();//;          //数据库中取的数据
    var dbSurfaceName;  //表名
    var userid;        //用户id
    var db;          //数据库
    var isLoadMore = true;  //是否加载更多
    var mState = 0;        //数据库 数组的加载View 的下载
    var mListView;        //ul
    var addParameter = [];     //记录app 传过来的数据
    var addParameterInt = 0;  //记录app 传过来几条数据
    apiready = function() {
        newsListBack();
        listenerScrollBottom();
        setData();
    }

    /**
    *加载View
    *type 调用类型  1为app传过来的数据  2、3为本地数据
    *data 为要加载的数据源
    *start 数据源的起始值 end结束值
    */
    function setView(type,data,start,end) {
        var itemConText = document.getElementById('lxb_div_abroad_itemConText').innerHTML;
        console.log('........data.....1......' + data.length+'..start..'+start+'..end..'+end);
        for (var i = start; i < end; i++) {
            console.log('........data.....1......i..' + i);
            var li = document.createElement('li');
            li.innerHTML = itemConText;
            var name = li.getElementsByClassName('abroan_item_right1_left')[0];  //标题
            var context = li.getElementsByClassName('abroan_item_right2')[0];   //内容
            var time = li.getElementsByClassName('abroan_item_right1_right')[0];     //时间
            var left1 = li.getElementsByClassName('lxb_div_abroan_item_left1')[0];  //图标
            var left2 = li.getElementsByClassName('lxb_div_abroan_item_left2')[0]; //小红点
            var id = li.getElementsByClassName('abroan_item_right3')[0]; //id
            if(data[i] == '{}' || ""){
              continue;
            }
            if(type == 1){
                  var data1 = JSON.parse(data[i]);
            }else if(type == 2 || type == 3){
                  var data1 = data[i].context;
                  var liItemID = data[i].id;
                  data1 = JSON.parse(data1);
                  id.innerText = liItemID;
            }
            //注册点击事件
            (function(i,type) {
                li.addEventListener('click', function(e) {
                  liOnListener(i,type);
                }, false);
            })(i,type);

            name.innerText = data1.content.portTitle;
            context.innerText = data1.content.explain;

            if(data1.content.appTime == undefined){
                time.innerText = getAppTime();
            }else {
                time.innerText = data1.content.appTime;
            }

            setLiLeftView(left1,left2,type,data1.keyword,data1.content.titlePic,data1.content.clickStatus);
            $('.lxb_div_abroad_context').append(li);
        }

        if (type == 1) {
            queryDb();
        }

        if(type == 3){
          isLoadMore = true;
        }

        if(type == 2 || type == 3){mState ++;}
    }

    //设置左边的View
    //view1 图标  view2 红点
    //type 那里调用 typeView 类型 pic图标地址 clickStatus是否要显示红点
    function setLiLeftView(view1,view2,type,typeView,pic,clickStatus){
      console.log('.....typeView....'+typeView+'..pic..'+pic+'...clickStatus....'+clickStatus+'....type...'+type);
          if(type == 1){
            if(typeView == 'push-saveVip' || typeView == 'push-outVip' || typeView == 'push-saveCombo' || typeView == 'push-saveLongtime' || typeView == 'push-spendLongtime'){
              view1.style.backgroundImage = "url(../image/nwes3.png)";
            }else if(typeView == 'push-gotoUrl'){
              if(pic == ''){
                  view1.style.backgroundImage = "url(../image/news1.png)";
              }else {
                  view1.style.backgroundImage = pic;
              }
            }else if(typeView == 'push-alerts'){
                view1.style.backgroundImage = "url(../image/nwes4.png)";
            }else {
              view1.style.backgroundImage = "url(../image/nwes3.png)";
            }

          }else if (type == 2){
            if(typeView == 'push-saveVip' || typeView == 'push-outVip' || typeView == 'push-saveCombo' || typeView == 'push-saveLongtime'){
              view1.style.backgroundImage = 'url(../image/nwes3.png)';
            }else if(typeView == 'push-gotoUrl'){
              if(pic == ''){
                  view1.style.backgroundImage = "url(../image/news1.png)";
              }else {
                  view1.style.backgroundImage = pic;
              }
            }else if(typeView == 'push-alerts'){
                view1.style.backgroundImage = "url(../image/nwes3.png)";
            }else {
              view1.style.backgroundImage = "url(../image/nwes3.png)";
            }

            if(clickStatus !=1){
              view2.style.display = 'none';
            }
          }
    }

    //li 的点击事件
    function liOnListener(i,type){
      console.log('....i...'+i);
      console.log('....type...'+type);
           switch (type) {
             case 1:
                var data1 = JSON.parse(appJson[i]);
                apiOpenWin(data1);
                console.log('.....数据库...'+dbData);
                if(data1.content.clickStatus == 1){
                  if(typeof(dbData) == 'undefined'){
                    if(addParameterInt == 0){
                      queryItem(i+1,2);
                      cancelReddot(i);
                    }else {
                      queryItem(addParameterInt+i+1,2);
                      cancelReddot(addParameterInt+i);
                    }
                  }else {
                    if(addParameterInt == 0){
                      queryItem(dbData.length+i+1,2);
                      cancelReddot(i);
                    }else {
                        queryItem(dbData.length+i+1,2);
                        cancelReddot(addParameterInt+i);
                    }
                  }
                }
                break;
             case 2 || 3:
                var data1 = dbData[i].context;
                data1 = JSON.parse(data1);
                apiOpenWin(data1);
                console.log('..............appJson..............'+appJson.length);
                if(data1.content.clickStatus == 1){
                  if(appJson.length == -1){
                    var ii = cancelReddot(i+addParameterInt);
                    queryItem(ii,2);
                  }else {
                    var ii = cancelReddot(appJson.length+addParameterInt+i);
                    queryItem(ii,2);
                  }

                }
                break;
                case 4:
                  apiOpenWin(addParameter[i]);
                  if(typeof(dbData) == 'undefined'){
                      queryItem(appJson.length+i+1,2);
                      cancelReddot(addParameterInt-i-1);
                  }else {
                    queryItem(dbData.length+appJson.length+i+1,2);
                    cancelReddot(addParameterInt-i-1);
                  }
                break;
            break;
             default:
           }
        }

  //点击时取消红点
  function cancelReddot(i){
    console.log('........i........'+i);
    var dv = document.getElementsByClassName('lxb_div_abroad')[0];
    var ularr = dv.getElementsByTagName("ul");              // 获取div下的ul
    var liarr = ularr[0].getElementsByTagName("li");      // 得到ul下的li
    var view2 = liarr[i].getElementsByClassName('lxb_div_abroan_item_left2')[0]; //小红点
    var id = liarr[i].getElementsByClassName('abroan_item_right3')[0].innerText;
    console.log('........id........'+id);
    view2.style.display = 'none';
    return id;
  }

   //打开一个窗口
   function apiOpenWin(data){
     console.log('......打开一个窗口........'+data);
     api.openWin({
         name: 'deposit',
         url: './deposit.html',
         pageParam: {
             name: data
         }
     });
   }

    function setData() {
        var divHeight = api.winHeight - 65;
        $('.lxb_div_abroad').css("height",divHeight+"px");
        userid = $api.getStorage('altairUserid');
        dbSurfaceName = 'altairNews' + userid;
        appJson = $api.getStorage('appJsonData');
        mListView = document.getElementsByClassName('lxb_div_abroad_context')['0'];

          if(judgeDataCorrect(appJson)){
            appJson = JSON.parse(appJson);
            if(appJson.length > 0){
                    db = api.require('db');
                    setView(1,appJson,0,appJson.length);
            }else {
              db = api.require('db');
              queryDb();
            }
          }else {
            db = api.require('db');
            queryDb();
          }
        console.log('........从app中拿来的数据...........' + appJson);
    }

    //操作数据库
    function operationDB() {
        //建表
        db.executeSql({
            name: 'altairNews',
            sql: "CREATE TABLE " + dbSurfaceName + "(id INTEGER PRIMARY KEY,context TEXT,iden INTEGER(255))"
        }, function(ret, err){
            if (ret.status) {
                console.log('...创建表成功..' + JSON.stringify(ret));
            } else {
                console.log('...创建表失败..' + JSON.stringify(err));
            }
        });

        window.setTimeout(function() {
            addData(appJson,0);
        },500);

    }

    //查询出某一条数据 并对状态进行更改 再保存在数据库
    //item 数据库中的哪一条数据  要更改的值
    function queryItem(item,value){
      var querySql = 'SELECT * FROM '+dbSurfaceName+' WHERE id = '+item;
      console.log('....querySql..'+querySql);
      db.selectSql({
          name: 'altairNews',
          sql: querySql
      }, function(ret, err) {
          if (ret.status) {
              var contentData = ret.data;
              contentData = contentData[0].context;
              contentData = JSON.parse(contentData);
              contentData.content.clickStatus = value;
              contentData = JSON.stringify(contentData);
              console.log('.....修改后的数据....context..' + contentData);
              upadteData(item,contentData);

          } else {
              console.log('.....查询表失败......' + JSON.stringify(err));
          }
      });
    }

    //更新数据
    function upadteData(id,context){
      var upadteSql = "UPDATE "+dbSurfaceName+" SET context = '"+context +"' WHERE id = "+id;
      console.log('....upadteSql..'+upadteSql);
      db.selectSql({
          name: 'altairNews',
          sql: upadteSql
      }, function(ret, err) {
          if (ret.status) {
              console.log('.....更新表成功...');
          } else {
              console.log('.....更新表失败......' + JSON.stringify(err));
          }
      });
    }

    //向数据库中插入数据 0 代表是app启动时传来的参数 1 代表启动后传来的参数
    function addData(data,type) {
      console.log('.......addData.......'+type);
      if(type == 0){
        var addDatalength = data.length;
      }else if(type == 1){
        var addDatalength = 1;
      }
        for (var i = 0; i < addDatalength; i++) {
            if(type == 0){
              var data1 = data[i];
              if(data1 == "{}"|| data1 == "" ){
                return;
              }
              var data2 = JSON.parse(data1);
              data2.content.appTime = getAppTime();
              data1 = JSON.stringify(data2);
            }else if(type == 1){
             data.content.appTime = getAppTime();
             var data1 = JSON.stringify(data);
             var data2 = data;
            }
            var usersql = "INSERT INTO " + dbSurfaceName + "(context,iden) values(" +"'" +data1 + "',"+"'"+data2.iden+"'"+")";
            console.log('...数据插入sql..' + usersql);
            db.executeSql({
                name: 'altairNews',
                sql: usersql
            }, function(ret, err) {
                if (ret.status) {
                    console.log("......插入数据成功..." + JSON.stringify(ret));
                } else {
                    console.log("......插入数据失败..." + JSON.stringify(err));
                }
            });
        }
    }

    //获取系统时间
    function getAppTime(){
      var now = new Date();

      var year = now.getFullYear();       //年
      var month = now.getMonth() + 1;     //月
      var day = now.getDate();            //日

      var hh = now.getHours();            //时
      var mm = now.getMinutes();          //分
      var ss = now.getSeconds();           //秒

      var clock = year + "-";

      if(month < 10)
          clock += "0";

      clock += month + "-";

      if(day < 10)
          clock += "0";

      clock += day + " ";

      if(hh < 10)
          clock += "0";

      clock += hh + ":";
      if (mm < 10) clock += '0';
      clock += mm + ":";

      if (ss < 10) clock += '0';
      clock += ss;
      return(clock);
    }

    //查询数据库
    function queryDb() {
        //打开数据库
        db.openDatabase({
            name: 'altairNews',
        }, function(ret, err){
            if (ret.status){
                console.log('.....打开数据库成功......' + JSON.stringify(ret));
                console.log('.....查询表...spl...' + "SELECT * FROM " + dbSurfaceName);
                //数据库的查询
                db.selectSql({
                    name: 'altairNews',
                    sql: "SELECT * FROM " + dbSurfaceName+" ORDER BY id DESC"
                }, function(ret, err) {
                    if (ret.status) {
                        screenDbData(ret.data);
                        console.log('.....查询表成功....dbData..' + dbData);
                        console.log('.....查询表成功......' + JSON.stringify(ret));
                        if(dbData.length > 10){
                          setView(2,dbData,mState,10);
                        }else {
                          setView(2,dbData,mState,dbData.length);
                        }
                        operationDB();
                    } else {
                        operationDB();
                        console.log('.....查询表失败......' + JSON.stringify(err));
                    }
                });
            } else {
                console.log('.....打开数据库失败......' + JSON.stringify(err));
            }
        });
    }

    //对数据库查出的数据 把有红点的数据放在前面
    function screenDbData(data){
      var recordReddotSubscript = 0;  //记录数组中最后带红点的对象的下标
      for (var i = 0; i < data.length; i++) {
         var data1 = data[i].context;
         data1  = JSON.parse(data1);
         console.log('.........clickStatus........'+data1.content.clickStatus);
          if(data1.content.clickStatus == 1){
            if(i == 0){
                dbData.push(data[i]);
            }else {
              console.log('.........插入........'+recordReddotSubscript);
              dbData.splice(recordReddotSubscript,0,data[i]);
            }
            recordReddotSubscript++;
          }else {
              dbData.push(data[i]);
          }
      }
    }

    //判断传过来的值是否正确  typeof(dbData) == 'undefined'
    function judgeDataCorrect(dataJSON){
       if(dataJSON === {} || dataJSON === '' || typeof(dataJSON) == 'undefined'){
         return false;
       }else {
         return true;
       }
    }

    //监听返回的事件
    function newsListBack() {
        //html页面a：
        api.addEventListener({
            name: 'newsListBack'
        }, function(ret, err) {
            console.log(".......newsListBack........");
            if(db == undefined){
              api.closeWin();
            }else {
              db.closeDatabase({
                  name: 'altairNews'
              }, function(ret, err) {
                  if (ret.status) {
                    api.closeWin();
                     console.log("......关闭数据库成功........");
                  } else {
                    api.closeWin();
                  }
              });
            }
        });

    }

    //设置“滑动到底部”事件监听
    function listenerScrollBottom() {
        api.addEventListener({
            name: 'scrolltobottom',
            extra: {
                threshold: 20 //设置距离底部多少距离时触发，默认值为0，数字类型
            }
        }, function(ret, err) {
            //判断列表是否已经到达屏幕底部，是，就代表可以加载更多；否，就不让加载更多。
              console.log('...........到底部了..........1');
            if (mListView.offsetHeight >= api.frameHeight && isLoadMore) {
              if(typeof(dbData) != 'undefined'){
                if(dbData.length > mState*10+10){
                  isLoadMore = false;
                  setView(3,dbData,mState*10,mState*10+10);
                }else {
                  if(dbData.length > mState*10){
                    isLoadMore = false;
                    setView(3,dbData,mState*10,dbData.length);
                  }
                }
              }
                console.log('...........到底部了..........2');
            }
        });
        api.addEventListener({
            name: 'pullData'
        }, function(ret, err) {
            if (ret) {
                var appData = ret.value;
                console.log('.......收到原生的信息..........' + JSON.stringify(ret));
                if(api.systemType === 'ios'){
                  appData = JSON.parse(appData);
                }
                addParameter[addParameterInt] = appData;
                appDataHandle(addParameter[addParameterInt]);
                addParameterInt ++ ;

            } else {
                console.log('.......收到原生的信息..出错........' + JSON.stringify(err));
            }
        });

    }

    //接收到原生发送的数据之后的处理
    function appDataHandle(data){
      var clickii = 4;
      console.log('.....data.......'+data);
      api.sendEvent({name:'receiveMessage'});
      var itemConText = document.getElementById('lxb_div_abroad_itemConText').innerHTML;
          var li = document.createElement('li');
          li.innerHTML = itemConText;
          var name = li.getElementsByClassName('abroan_item_right1_left')[0];  //标题
          var context = li.getElementsByClassName('abroan_item_right2')[0];   //内容
          var time = li.getElementsByClassName('abroan_item_right1_right')[0];     //时间
          var left1 = li.getElementsByClassName('lxb_div_abroan_item_left1')[0];  //图标
          var left2 = li.getElementsByClassName('lxb_div_abroan_item_left2')[0]; //小红点
          var id = li.getElementsByClassName('abroan_item_right3')[0]; //id
          //注册点击事件
            console.log('.....data.....3..');
          (function(addParameterInt,clickii) {
              li.addEventListener('click', function(e) {
                liOnListener(addParameterInt,clickii);
              },false);
          })(addParameterInt,clickii);
          name.innerText = data.content.portTitle;
          context.innerText = data.content.explain;
          console.log("........data1.....2...0.."+data.content.appTime);
          if(data.content.appTime == undefined){
          console.log("........data1.....2...1.."+getAppTime());
            time.innerText = getAppTime();
          }else {
          console.log("........data1.....2..2..."+data.content.appTime);
            time.innerText = data.content.appTime;
          }
          setLiLeftView(left1,left2,1,data.keyword,data.content.titlePic,data.content.clickStatus);
          var ularr = document.getElementsByClassName("lxb_div_abroad_context");              // 获取div下的ul
          var liarr = ularr[0].getElementsByTagName("li");      // 得到ul下的li
          ularr[0].insertBefore(li,liarr[0]);
          console.log('.....liarr.......'+liarr);
          addData(data,1);
  }

</script>

</html>
